import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
import 'package:trip_app/dao/home_dao.dart';
import 'package:trip_app/model/common_model.dart';
import 'package:trip_app/model/config_model.dart';
import 'package:trip_app/model/grid_nav_model.dart';
import 'package:trip_app/model/home_model.dart';
import 'package:trip_app/model/sales_box_model.dart';
import 'package:trip_app/pages/search_page.dart';
import 'package:trip_app/pages/speak_page.dart';
import 'package:trip_app/widget/grid_nav.dart';
import 'package:trip_app/widget/loading_contain.dart';
import 'package:trip_app/widget/local_nav.dart';
import 'package:trip_app/widget/sales_box.dart';
import 'package:trip_app/widget/search_bar.dart';
import 'package:trip_app/widget/sub_nav.dart';
const APPBAR_SCROLL_OFFSET=150;
const SEARCH_BAR_DEFAULT_TEXT = '网红打卡地 景点 酒店 美食';

class HomePage extends StatefulWidget {
  static ConfigModel configModel;
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  List<CommonModel> bannerList=[];
  List<CommonModel> localNavList=[];
  List<CommonModel> subNavList=[];
  GridNavModel gridNavModel;
  SalesBoxModel salesBox;
  SalesBoxModel salesBoxModel;
  String result="123";
  bool _loading = true;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    loadData();
  }

  loadData() async {
    try{
      HomeModel model=await HomeDao.fetch();
      setState(() {
        result=json.encode(model.config);
        HomePage.configModel = model.config;
        print("model="+model.config.toString());
        bannerList=model.bannerList;
        localNavList=model.localNavList;
        gridNavModel=model.gridNav;
        salesBoxModel = model.salesBox;
        subNavList=model.subNavList;
        salesBox=model.salesBox;
        _loading=false;
      });
    }catch(e){
      print("e="+e.toString());
      setState(() {
        _loading = false;
      });
    }
  }

  double  appBarAlpha=0;
  _onScroll(offset){
    double alpha=offset/APPBAR_SCROLL_OFFSET;
    if(alpha<0){
      alpha=0;
    }else if(alpha>1){
      alpha=1;
    }
    setState((){
      appBarAlpha=alpha;
    });

  }


  Future<Null> _handleRefresh() async {
    try {
      HomeModel model = await HomeDao.fetch();
      setState(() {
        HomePage.configModel = model.config;
        localNavList = model.localNavList;
        subNavList = model.subNavList;
        gridNavModel = model.gridNav;
        salesBoxModel = model.salesBox;
        bannerList = model.bannerList;
        _loading = false;
      });
    } catch (e) {
      print(e);
      setState(() {
        _loading = false;
      });
    }
    return null;
  }


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: LoadingContainer(
          isLoading: _loading,
          child: Stack(
            children: <Widget>[
              MediaQuery.removePadding(
                removeTop: true,
                context: context,
                child: RefreshIndicator(
                    onRefresh: _handleRefresh,
                    child: NotificationListener(
                      // ignore: missing_return
                      onNotification: (scrollNotification) {
                        if (scrollNotification is ScrollUpdateNotification &&
                            scrollNotification.depth == 0) {
                          //滚动且是列表滚动的时候
                          _onScroll(scrollNotification.metrics.pixels);
                        }
                      },
                      child: _listView,
                    )),
              ),
              _appBar
            ],
          )),
    );
  }

   _onTextChange(String value) {
  }

  Widget get _appBar{
    return  Column(
      children: <Widget>[
        Container(
          decoration: BoxDecoration(
            gradient: LinearGradient(
              //AppBar渐变遮罩背景
              colors: [Color(0x66000000), Colors.transparent],
              begin: Alignment.topCenter,
              end: Alignment.bottomCenter,
            ),
          ),
          child: Container(
            padding: EdgeInsets.fromLTRB(0, 10, 0, 0),
            height: 80.0,
            decoration: BoxDecoration(
              color: Color.fromARGB((appBarAlpha * 255).toInt(), 255, 255, 255),
            ),
            child: SearchBar(
              searchBarType: appBarAlpha > 0.2
                  ? SearchBarType.homeLight
                  : SearchBarType.home,
              inputBoxClick: _jumpToSearch,
              speakClick: _jumpToSpeak,
              defaultText: SEARCH_BAR_DEFAULT_TEXT,
              leftButtonClick: () {},
            ),
          ),
        ),
        Container(
            height: appBarAlpha > 0.2 ? 0.5 : 0,
            decoration: BoxDecoration(
                boxShadow: [BoxShadow(color: Colors.black12, blurRadius: 0.5)]))
      ],
    );
  }

  Widget get _listView{
    return ListView(
      children: <Widget>[
        Column(
          children:<Widget> [
           _banner,
            Padding(
              padding:EdgeInsets.fromLTRB(7, 4, 7, 4),
              child: LocalNav(localNavList: localNavList,),
            ),
            Padding(
              padding: EdgeInsets.fromLTRB(7, 4, 7, 4),
              child: GridNav(gridNavModel: gridNavModel,),
            ),
            Padding(
              padding: EdgeInsets.fromLTRB(7, 4, 7, 4),
              child: SubNav(subNavList: subNavList,),
            ),
            Padding(
              padding: EdgeInsets.fromLTRB(7, 4, 7, 4),
              child: SalesBox(salesBox: salesBox,),
            )
          ],
        ),
      ],
    );
  }

  Widget get _banner{
    return  Container(
      height: 180,
      child: Swiper(
        itemCount: bannerList.length,
        autoplay: true,
        itemBuilder: (BuildContext context,int index) {
          return Image.network(
            bannerList[index].icon,
            fit: BoxFit.fill,
          );
        },
        pagination: SwiperPagination(),
      ),
    );
  }

  _jumpToSpeak() {
    return Navigator.push(context,
    MaterialPageRoute(builder: (context)=>SpeakPage())
    );
  }

  _jumpToSearch() {
    return Navigator.push(context,
        MaterialPageRoute(builder: (context){
          return SearchPage(hint:SEARCH_BAR_DEFAULT_TEXT,);
        }));
  }
}
